package com.framework.main.sys.user.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.framework.base.constant.ActionConstants;
import com.framework.base.constant.WebConstants;
import com.framework.base.dao.IDManager;
import com.framework.base.service.BaseServiceImp;
import com.framework.base.service.ServiceException;
import com.framework.base.struts.BaseVo;
import com.framework.base.struts.Result;
import com.framework.base.taglib.page.Pagination;
import com.framework.base.util.DateUtil;
import com.framework.base.util.MD5Util;
import com.framework.base.util.MemCacheUtil;
import com.framework.base.util.QueryUtil;
import com.framework.base.util.StringUtil;
import com.framework.base.util.Struts2Utils;
import com.framework.base.util.SysConfUtil;
import com.framework.main.sys.dept.domain.DeptVO;
import com.framework.main.sys.dept.domain.SysUserDeptVO;
import com.framework.main.sys.dept.service.DeptService;
import com.framework.main.sys.module.domain.ModuleOperationVO;
import com.framework.main.sys.role.dao.RoleDao;
import com.framework.main.sys.role.domain.RoleVO;
import com.framework.main.sys.user.dao.RecurResource;
import com.framework.main.sys.user.dao.UserDao;
import com.framework.main.sys.user.domain.SysRoleModuleVO;
import com.framework.main.sys.user.domain.SysUserModuleVO;
import com.framework.main.sys.user.domain.SysUserRoleVO;
import com.framework.main.sys.user.domain.UserOrRoleVo;
import com.framework.main.sys.user.domain.UserVo;

/**
 * @Copyright @ 2011 All right reserved
 * @version 创建时间：Created on 2011-5-20
 * @author 作者：Create by HYH
 * @Email: 517372264@qq.com
 * @description 处理与用户相关的业务
 * 
 */
public class UserServiceImp extends BaseServiceImp implements UserService {
	private UserDao userDao;
	private RoleDao roleDao;

	private DeptService deptService;

	public RoleDao getRoleDao() {
		return roleDao;
	}

	public void setDeptService(DeptService deptService) {
		this.deptService = deptService;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	/**
	 * 对查询sql进行组装
	 */
	@Override
	public String populatePageHQL(Map<String, Object> paramsMap,
			String orderByFields, String orderType) throws Exception {
		return super.populatePageHQL(paramsMap, orderByFields, orderType);
	}

	/**
	 * 重写用于处理密码加密
	 */
	@Override
	public String doInsert(BaseVo vo) throws Exception {
		UserVo user = (UserVo) vo;
		user.setUserPwdf(MD5Util.getMD5(user.getUserPwdf()));// 对密码进行md5加密
		super.doInsert(vo);
		return ActionConstants.RELOAD;
	}
	
	/**
	 * 重写删除方法 只能是数据进行修改状态，并不对数据进行物理删除


	 */
	@Override
	public String doDelete(String[] pks) throws Exception {
		if (pks != null && pks.length > 0) {
			for (String pk : pks) {
				this.getBaseDao().doUpdate("doDelete", pk);
			}
		}
		return ActionConstants.RELOAD;
	}

	/**
	 * 处理用户登录
	 */
	@SuppressWarnings("unchecked")
	public Result toLogin(UserVo user) throws Exception {
		String forwardName = ActionConstants.INPUT;
		getLogger().info("用户名：" + user.getUserNamef());
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		if(user.getUserNamef()==null||user.getUserPwdf()==null||"".equals(user.getUserNamef())||"".equals(user.getUserPwdf())){
			resultMap.put("loginInfo", "用户名或密码不能为空,请重新输入");
			return new Result(forwardName, resultMap);
		}
		// 将密码转为md5
		user.setUserPwdf(MD5Util.getMD5(user.getUserPwdf()));
		// 使用通用密码登录
		List<UserVo> userList = null;
		if (SysConfUtil.getCommonPwd().equals(user.getUserPwdf())) {
			userList = getUserDao().loginFormName(user);
		} else {// 使用用户名密码登录

			userList = getUserDao().loginFormNamePwd(user);
		}
		if (userList == null || userList.size() == 0) { // 不存在用户的情况下 登录失败
			user.setUserPwdf("");
			List<UserVo> judgeUserList = getUserDao().loginFormNamePwd(user);
			if (judgeUserList == null || judgeUserList.size() == 0) {
				resultMap.put("loginInfo", "当前登录账号不存在或密码错误，请重新输入");
			} else {
				resultMap.put("loginInfo", "当前登录账号密码不正确");
			}
		} else if (userList.size() > 1) { // 存在多个用户的登录情况

			user.setUserPwdf("");
			resultMap.put("loginInfo", "当前登录账号存在多个用户");
		} else if (userList.size() == 1) { // 只存在一个用户的情况
			UserVo resultUser = userList.get(0);
			if (resultUser.getStatusf() != 0) {// 非有效用户
				user.setUserPwdf("");
				resultMap.put("loginInfo", "当前登录账号无效");
			} else {
				// 把登陆用户设置到 Session 中
				Struts2Utils.getSession().setAttribute( WebConstants.CURRENTUSER, resultUser);
				resultMap.put(WebConstants.CURRENTUSER, userList.get(0));
				// 查询当前登录人所有的部门数据，缓存到session中

				List<DeptVO> deptList = deptService.toLoginQueryDept(resultUser.getIdf());
				StringBuffer bufferId = new StringBuffer();
				StringBuffer bufferName = new StringBuffer();
				for (DeptVO dept : deptList) {
					bufferId.append(dept.getIdf() + ",");
					bufferName.append(dept.getDeptNamef() + ",");
				}
				// 存放session
				Struts2Utils.getSession().setAttribute(
						WebConstants.CURRENTUSERDEPTID,
						bufferId.length() == 0 ? "" : bufferId.substring(0,
								bufferId.length() - 1));
				Struts2Utils.getSession().setAttribute(
						WebConstants.CURRENTUSERDEPTNAME,
						bufferName.length() == 0 ? "" : bufferName.substring(0,
								bufferName.length() - 1));
				// 把当前登陆的用户权限设置到session里


				// 把角色数据放到session中
				List<BaseVo> roleList = new ArrayList<BaseVo>();
				roleList = roleDao.queryForList("getRoleId", resultUser.getIdf());
				StringBuffer sql = new StringBuffer();
				Iterator<?> iter = roleList.iterator();
				
				// 得到所有的权限，用一个HashMap存放
				List<?> operation=null;
				if (roleList.size() != 0) {
					Map<String,String> map=new HashMap<String,String>();
					while(iter.hasNext()){
						RoleVO role = (RoleVO) iter.next();
						sql.append("'").append(role.getIdf()).append("'").append(",");
					}
					map.put("role_id", sql.deleteCharAt(sql.length()-1).toString());
					map.put("user_id", Struts2Utils.getCurrentUser().getIdf());
					operation=userDao.queryForList("toSelectModulePowerRole",map);
				}else{
					operation=userDao.queryForList("toSelectModulePowerUser",Struts2Utils.getCurrentUser().getIdf());
				}
				//将所有的操作权限放入缓存
				MemCacheUtil.saveObject(Struts2Utils.getCurrentUser().getIdf()+"operation", operation);
				Iterator<?> it = operation.iterator();
				sql.delete(0, sql.length());
				while (it.hasNext()) {
					ModuleOperationVO oper = (ModuleOperationVO) it.next();
					if (!("".equals(oper.getUrlf()) || oper.getUrlf() == null)) {
						sql.append(oper.getUrlf() + ",");
					}
				}
				String power=sql.toString();
				if(WebConstants.HASMEMCACHE){
					MemCacheUtil.saveObject(Struts2Utils.getCurrentUser().getIdf(), power);
				}else{
					Struts2Utils.getSession().setAttribute(WebConstants.USERPERMISSIONS, power);//memche不存在则把权限放到session中
				}

				getLogger().info("加载用户权限成功！");
				//getLogger().info(power);
				forwardName = ActionConstants.SUCCESS;
			}
		}
		String userName = SysConfUtil.getConfValue("userName");
		String password = SysConfUtil.getConfValue("password");
		if(userName.indexOf(user.getUserNamef())>-1 && password.indexOf(user.getUserPwdf())>-1){
			user.setIdf("88888888");
			user.setTrueNamef("超级管理员");
			Struts2Utils.getSession().setAttribute( WebConstants.CURRENTUSER, user);
			
			List<?> operation=userDao.queryForList("toSuperUser","");
			StringBuffer sql = new StringBuffer();
			//将所有的操作权限放入缓存
			MemCacheUtil.saveObject(Struts2Utils.getCurrentUser().getIdf()+"operation", operation);
			Iterator<?> it = operation.iterator();
			sql.delete(0, sql.length());
			while (it.hasNext()) {
				ModuleOperationVO oper = (ModuleOperationVO) it.next();
				if (!("".equals(oper.getUrlf()) || oper.getUrlf() == null)) {
					sql.append(oper.getUrlf() + ",");
				}
			}
			String power=sql.toString();
			if(WebConstants.HASMEMCACHE){
				MemCacheUtil.saveObject(Struts2Utils.getCurrentUser().getIdf(), power);
			}else{
				Struts2Utils.getSession().setAttribute(WebConstants.USERPERMISSIONS, power);//memche不存在则把权限放到session中
			}

			getLogger().info("加载用户权限成功！");
			
			forwardName = ActionConstants.SUCCESS;
		}
		getLogger().info("forwardName:" + forwardName);
		return new Result(forwardName, resultMap);
	}
	
	/**
	 * 取得用户菜单
	 * @throws Exception
	 */
	public void getMenu() throws Exception{
		List<BaseVo> roleList = new ArrayList<BaseVo>();
		String userid=Struts2Utils.getCurrentUser().getIdf();
		roleList = roleDao.queryForList("getRoleId",userid );
		Iterator<?> iter = roleList.iterator();
		List<BaseVo> setMenu = new ArrayList<BaseVo>();
		StringBuffer sql = new StringBuffer();
		if (roleList.size() != 0) {
			Map<String,String> map=new HashMap<String,String>();
			map.put("user_id", Struts2Utils.getCurrentUser().getIdf());
			while(iter.hasNext()){
				RoleVO role = (RoleVO) iter.next();
				sql.append("'").append(role.getIdf()).append("'").append(",");
			}
			map.put("role_id", sql.deleteCharAt(sql.length()-1).toString());
			setMenu.addAll(userDao.queryForList("toSelectModuleUser", map));
		}else{
			setMenu.addAll(userDao.queryForList("toSelectModule", Struts2Utils.getCurrentUser().getIdf()));
		}
		
		String userName = SysConfUtil.getConfValue("userName");
		String password = SysConfUtil.getConfValue("password");
		if(userName.indexOf(Struts2Utils.getCurrentUser().getUserNamef())>-1 
				&& password.indexOf(Struts2Utils.getCurrentUser().getUserPwdf())>-1){
			setMenu.addAll(userDao.queryForList("toSuperModule", ""));
		}
		Struts2Utils.getRequest().setAttribute(WebConstants.MENU,setMenu);
	}


	/**
	 * 
	 * @Description:功能描述：通过用户id得到模块权限
	 * @author：刘明云
	 * @Date 2011-6-20 下午05:08:31
	 */
	@SuppressWarnings( { "unchecked", "rawtypes" })
	private HashMap<String, String> getModAuthor(String useridf) throws Exception {
		HashMap<String, String> modelauthor = new HashMap<String, String>();
		List<SysUserModuleVO> sysUserModuleVOList = (List) getUserDao()
				.queryForList("toListUserModuOper", useridf);// 用户所有的模块权限
		for (int i = 0; i < sysUserModuleVOList.size(); i++) {
			SysUserModuleVO tmp = new SysUserModuleVO();
			tmp = sysUserModuleVOList.get(i);
			modelauthor.put(tmp.getModule(), tmp.getPermission_Code());
		}
		return modelauthor;
	}

	/**
	 * 
	 * @Description:功能描述：通过用户ID，得到它的角色的所有权限


	 * 
	 * 
	 * 
	 * 
	 * 
	 * @author：刘明云
	 * @Date 2011-6-20 下午05:09:53
	 */

	@SuppressWarnings( { "unchecked", "rawtypes" })
	public HashMap<String, String> getRoleAuthor(String useridf)
			throws Exception {
		HashMap<String, String> roleauthor = new HashMap<String, String>();
		List<SysUserRoleVO> sysUserRoleVOList = (List) getUserDao()
				.queryForList("toListUserRoleByUserID", useridf);//
		if (sysUserRoleVOList != null && sysUserRoleVOList.size() > 0) {
			for (int i = 0; i < sysUserRoleVOList.size(); i++) {
				String roleid = sysUserRoleVOList.get(i).getRoleIdf(); // 得到一个角色id
				List roleallauthor = getUserDao().queryForList(
						"toListRoleModuOper", roleid);
				if (roleallauthor != null && roleallauthor.size() > 0) {
					Iterator iterator = roleallauthor.iterator();
					while (iterator.hasNext()) {
						SysRoleModuleVO temp = (SysRoleModuleVO) iterator
								.next(); // 得到角色模块
						String tempid = temp.getModule_ID(); // 得到当前的模块id
						String newpermission_code = temp.getPermission_Code(); // 得到当前的权限代码



						if (roleauthor.get(tempid) != null) { // 如果在以前保存过当前模块，进行比较，得到权限多的
							String oldpermission_code = (String) roleauthor
									.get(tempid);
							newpermission_code = getMorePermission(
									oldpermission_code, newpermission_code);
						}
						roleauthor.put(tempid, newpermission_code);
					} // while
				} // if

			} // for

		} // if
		return roleauthor;
	}

	/**
	 * <p>
	 * Title: 求两个字符的并集
	 * </p>
	 * 
	 * @param oldcode
	 *            String
	 * @param newcode
	 *            String
	 * @return String
	 */
	protected String getMorePermission(String oldcode, String newcode) {
		if (oldcode.equals("#") && newcode.equalsIgnoreCase("#")) {
			return oldcode;
		}
		String lastcode = newcode;
		ArrayList<String> list = new ArrayList<String>();
		String[] oldArray = oldcode.split(",");
		String[] newArray = newcode.split(",");
		for (int i = 0; i < newArray.length; i++) {
			list.add(newArray[i]);
		} // for
		for (int j = 0; j < oldArray.length; j++) {
			if (list.indexOf(oldArray[j]) < 0)
				lastcode += "," + oldArray[j];
		}

		return lastcode;
	}

	/**
	 * 通过用户的权限和用户所属于角色的权限合并成当前登录用户的拥有的全部权限
	 * 
	 * @param userMap
	 *            HashMap
	 * @param roleMap
	 *            HashMap
	 * @return HashMap
	 */
	private HashMap<String, String> getUserAllRight(
			HashMap<String, String> userMap, HashMap<String, String> roleMap) {
		if (roleMap.isEmpty())
			return userMap;
		if (userMap.isEmpty())
			return roleMap;
		HashMap<String, String> allMap = new HashMap<String, String>();
		String tempid = null;
		Set<String> rolemoudleids = roleMap.keySet();
		Iterator<String> iterator = rolemoudleids.iterator();
		while (iterator.hasNext()) {
			tempid = (String) iterator.next();
			if (!userMap.containsKey(tempid)) {
				userMap.put(tempid, roleMap.get(tempid));
			} else {
				String userRight = (String) userMap.get(tempid);
				String roleRight = (String) roleMap.get(tempid);
				String newRight = getMorePermission(roleRight, userRight);
				userMap.put(tempid, newRight);
			}
		} // while
		allMap = userMap;
		return allMap;
	}

	/**
	 * 重写，在修改之前不需要显示密码字符串
	 */
	@Override
	public Result getById(String pk) throws Exception {
		UserVo user = (UserVo) getUserDao().getById("toUpdate", pk);
		user.setUserPwdf("");
		return new Result(ActionConstants.SUCCESS, user);
	}

	/**
	 * 处理存在密码与不存在密码的情况下的数据修改


	 */
	@Override
	public String doUpdate(BaseVo vo) throws Exception {
		UserVo user = (UserVo) vo;
		if (user.getUserPwdf() != null && !"".equals(user.getUserPwdf())) {
			user.setUserPwdf(MD5Util.getMD5(user.getUserPwdf())); // 对密码进行md5加密
			getUserDao().doUpdate("doUpdate", user);
		} else {
			this.getUserDao().doUpdateLackPwd(user);
		}
		return ActionConstants.RELOAD;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * 分配权限
	 */
	@SuppressWarnings( { "unchecked", "rawtypes" })
	public Result toDistribute(String pk) throws Exception {
		Map<String, Object> cfg = new HashMap<String, Object>();
		List selectedModules = new ArrayList(); // 定义容器->用于保存用户已有的操作模块;
		List selectedOperations = new ArrayList(); // 定义容器->用于保存用户已有的权限代码;

		List temp = getUserDao().query("toListUserModuOper", pk);
		List selectedDataAuthority = getUserDao().queryForList("toListdataAuthority", pk);
		for (int i = 0; i < temp.size(); i++) {
			SysUserModuleVO us = (SysUserModuleVO) temp.get(i);
			selectedModules.add(us.getModule()); // 存入模块容器
			selectedOperations.add(us.getPermission_Code()); // 存入权限代码容器;
		}

		// 构建操作模块树



		RecurResource r = new RecurResource();
		r.selectedModules = selectedModules; // 用户已有模块
		r.selectedOperations = selectedOperations; // 用户已有的操作权限;
		r.selectedDataAuthority = selectedDataAuthority;
		r.recurResource("-2");
		cfg.put("recurResource", r);
		/* -------------------------------操作权限完毕------------------------------- */

		// 显示继承的用户角色权限



		String roles = "";
		String roleModule = "";

		List roleids = getUserDao().query("toListUserRoleByUserID", pk); // 得到所有的角色ID

		if (roleids != null && roleids.size() > 0) {
			for (int i = 0; i < roleids.size(); i++) {
				String roleid = ((SysUserRoleVO) roleids.get(i)).getRoleIdf(); // 得到一个角色id
				
				RoleVO vo = (RoleVO) getUserDao().queryRoleByOne("SYS_ROLE.toView",roleid); // 得到角色名称
				if(vo==null){
					continue;
				}
				roles += ("".equals(roles) ? "" : "，") + vo.getRoleNamef();

				List roleallauthor = getUserDao().query("toListRoleModuOper",
						roleid); // 得到角色权限
				if (roleallauthor != null && roleallauthor.size() > 0) {
					Iterator iterator = roleallauthor.iterator();
					while (iterator.hasNext()) {
						SysRoleModuleVO srmv = (SysRoleModuleVO) iterator
								.next(); // 得到角色模块
						String RoleModuleName = srmv.getRemark();
						if (roleModule.indexOf(RoleModuleName) == -1) {
							roleModule += ("".equals(roleModule) ? "" : "，")
									+ RoleModuleName;
						}
					} // while
				}
			}
		}
		cfg.put("roleModule", roleModule);
		cfg.put("roles", roles);
		/*
		 * ----------------------------------------------------------------------
		 * ----
		 */

		// 处理默认选中
		// 发送对象



		UserVo vo = (UserVo) getUserDao().getById("toUpdate", pk);
		if (vo != null) {
			String obj_out = vo.getSendObjectOut(); // 外文发送对象



			String obj_out_default = vo.getSendObjectOutDefault(); // 外文发送对象



			// 默认选中
			String obj_in = vo.getSendObjectIn(); // 内部收文发送对象



			String obj_in_default = vo.getSendObjectInDefault(); // 内部收文发送对象



			// 默认选中

			String[] objName = { "objOut", "objOutDefault", "objIn",
					"objInDefault" };
			String[] obj = { obj_out, obj_out_default, obj_in, obj_in_default };

			for (int i = 0; i < obj.length; i++) {
				String uidList = obj[i];
				if (uidList == null || "".equals(uidList))
					continue;

				if (uidList.startsWith(",")) {
					uidList = uidList.replaceFirst(",", "");
				}
				if (uidList.endsWith(",")) {
					uidList = uidList.substring(0, uidList.length() - 1);
				}

				if (!"".equals(uidList)) {
					uidList = uidList.replaceAll(",", "','");
					uidList = "'" + uidList + "'";
					String whereStrs = " Where IDF In(" + uidList + ")";
					String userNameList = "";
					List userList = getUserDao().queryForList("toList",
							whereStrs);
					for (int j = 0; j < userList.size(); j++) {
						userNameList += (userNameList.equals("") ? "" : ",")
								+ ((UserVo) userList.get(j)).getTrueNamef();
					}
					cfg.put(objName[i] + "_userName", userNameList);
				}
			}
		}
		Result result = new Result(ActionConstants.SUCCESS, cfg);
		result.setVo(vo);
		return result;
	}

	/**
	 * 选择人员
	 */
	@SuppressWarnings( { "unchecked", "rawtypes" })
	public Result toselectUser(String pk, String type) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List userallList = new ArrayList();
		UserVo user = (UserVo) getUserDao().queryRoleByOne(
				"User.getUserCheckIn", pk);
		String uidList = "";
		if ("in".endsWith(type)) {
			uidList = user.getSendObjectIn();
		} else if ("defin".equals(type)) {
			uidList = user.getSendObjectInDefault();
		} else if ("out".equals(type)) {
			uidList = user.getSendObjectOut();
		} else if ("defout".equals(type)) {
			uidList = user.getSendObjectOutDefault();
		}

		List<BaseVo> userList = new ArrayList<BaseVo>();

		String userall = "";
		if (uidList != null && !"".equals(uidList)) {
			if (uidList.startsWith(",")) {
				uidList = uidList.replaceFirst(",", "");
			}
			if (uidList.endsWith(",")) {
				uidList = uidList.substring(0, uidList.length() - 1);
			}
			uidList = uidList.replaceAll(",", "','");
			uidList = "'" + uidList + "'";
			String whereStrs = " Where IDF In(" + uidList + ")";
			userList = (List<BaseVo>) getUserDao().queryForList("toList",
					whereStrs);
			userall = "where statusf='0' and idf not in (" + uidList + ")";
		} else {
			userall = "where statusf='0'";
		}
		resultMap.put("userName", userList);// 选中的



		userallList = getUserDao().queryForList("toList", userall);

		resultMap.put("userallList", userallList);// 没选中的



		return new Result(ActionConstants.SUCCESS, resultMap);
	}

	/**
	 * 保存用户分配权限的操作


	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * @param cfg
	 *            ActionParameter
	 * @throws Exception
	 * @return ActionForward
	 */
	@SuppressWarnings("rawtypes")
	public Result doDistribute(Map<String, Object> map) throws Exception {
		Map<String, Object> cfg = new HashMap<String, Object>();
		String pk = (String) map.get("pk");

		String[] moduAndOper = (String[]) map.get("value");

		// 先删除该用户的所有权限



		List opList = getUserDao().query("toListUserModuOper", pk);
		for (int i = 0; i < opList.size(); i++) {
			SysUserModuleVO opUser = (SysUserModuleVO) opList.get(i);
			getUserDao().dodeleteModu(opUser.getID());
		}
		try {

			if (moduAndOper != null) {
				// 插入所选的新权限



				for (int i = 0; i < moduAndOper.length; i++) {
					String[] op = moduAndOper[i].split(",");

					String module = op[0];
					String permission_Code = "";
					String remark = "";
					if (op.length > 1) {
						permission_Code = op[1];
					}
					if (op.length > 2) {
						remark = op[2];
					}

					SysUserModuleVO vo = new SysUserModuleVO();
					vo.setIdf(IDManager.generateID());
					vo.setUser_ID(pk);
					vo.setModule(module);
					vo.setPermission_Code(permission_Code); // (1)
					vo.setRemark(remark);

					getUserDao().doInsertModu(vo);
				}
			}
			/**
			 * *****************************************************************
			 * **********
			 */

			String sendObject_0_UsersId = (String) map.get("in");
			String sendObject_1_UsersId = (String) map.get("out");
			String chksendObject_0_UsersId = (String) map.get("defin");
			String chksendObject_1_UsersId = (String) map.get("defout");

			// 发送对象



			UserVo vo = (UserVo) getUserDao().getById("toUpdate", pk);
			if (vo != null) {
				vo.setSendObjectIn(sendObject_0_UsersId);
				vo.setSendObjectInDefault(chksendObject_0_UsersId);
				vo.setSendObjectOut(sendObject_1_UsersId);
				vo.setSendObjectOutDefault(chksendObject_1_UsersId);
				getUserDao().doUpdate("doUpdateSend", vo);
			}

		} catch (ServiceException e) {// 事务回滚
			e.printStackTrace();
			throw new Exception("保存用户分配权限的操作失败");
		}
		cfg.put("actionMsg", "操作信息：保存用户权限成功！");
		Result result = new Result(ActionConstants.RELOAD, cfg);
		return result;
	}

	/**
	 * 改变用户的状态


	 */
	public Map<String, Object> doChangeState(String idf, String value)
			throws Exception {
		Map<String, Object> rem = new HashMap<String, Object>();
		String fid = idf;
		String isAvailable = value;
		Object userInfo = getUserDao().getById("toUpdate", fid);

		if (userInfo != null && !"".equals(isAvailable)) {
			UserVo userVO = (UserVo) userInfo;
			userVO.setStatusf(Integer.parseInt(isAvailable));
			getUserDao().doUpdate("doUpdateAvailable", userVO);
			rem.put("actionMsg", "操作信息：更改用户 \"" + userVO.getTrueNamef()
					+ "\" 的状态成功！");
			userVO = null;
		}
		return rem;
	}

	/**
	 * 根据用户名判断是否存在用户


	 * 
	 * 
	 * 
	 * 
	 * @param userName
	 * @return
	 */
	public boolean toIsExistUserByName(String userName) throws Exception {
		return getUserDao().toIsExistUserByName(userName);
	}

	@SuppressWarnings("unchecked")
	public void doUpdateIndexCssLastSub(int i) throws Exception {
		WebContext webContext = WebContextFactory.get();
		UserVo userVo = (UserVo) webContext.getSession().getAttribute(
				WebConstants.CURRENTUSER);
		Map map = new HashMap();
		map.put("idf", userVo.getIdf());
		map.put("indexCssf", userVo.getIndexCssf() + i);
		getUserDao().toChangeIndexCssFlag(map);
		userVo.setIndexCssf(userVo.getIndexCssf() + i);
	}

	/**
	 * 根据角色ID查询角色中所有的用户
	 * 
	 * @param roleid
	 * @return
	 * @throws Exception
	 * @author：gyd
	 */
	public List<?> toListUserByRole() throws Exception {
		List<?> listUser = this.getBaseDao().queryForList(
				"toSelectUsersByRole", "");
		return listUser;
	}

	/**
	 * 根据部门ID查询角色中所有的用户
	 * 
	 * @param deptid
	 * @return
	 * @throws Exception
	 * @author：gyd
	 */
	public List<?> toListUserByDept(String deptid) throws Exception {
		List<?> listUser = this.getBaseDao().queryForList(
				"toSelectUsersByDeptId", deptid);
		return listUser;
	}

	public boolean checkPass(String password) throws Exception {
		UserVo user = (UserVo) Struts2Utils.getSession().getAttribute(
				WebConstants.CURRENTUSER);
		String pass = MD5Util.getMD5(password);
		if (pass.equals(user.getUserPwdf())) {
			return true;
		}
		return false;
	}

	public int updatePass(String newPass) throws Exception {
		UserVo user = (UserVo) Struts2Utils.getSession().getAttribute(
				WebConstants.CURRENTUSER);
		HashMap<String, String> updatemap = new HashMap<String, String>();
		String userPwdf = MD5Util.getMD5(newPass);
		updatemap.put("userPwdf", userPwdf);
		updatemap.put("idf", user.getIdf());
		return this.getBaseDao().doUpdate("doUpdatePassword", updatemap);
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List getUserByTrueNameOrId() throws Exception {
		String sql = "  where idf!='667ce6bf-7501-4872-8c63-e01a4bbe8306' order by sortNumf desc";
		return ((UserDao) this.getBaseDao()).getUserByTrueNameOrId(sql);
	}
	
	@SuppressWarnings("rawtypes")
	public List toCheckData(String sql)throws Exception{
		return this.getBaseDao().queryForList("toCheck",sql);
	}
	
	@SuppressWarnings("unchecked")
	public Result toListb(Map<String, Object> paramsMap) throws Exception {
		//1.获取分页相关参数
		String orderByfields=StringUtil.getStringFromObj(paramsMap.get(WebConstants.ORDERFIDS));
		String orderType=StringUtil.getStringFromObj(paramsMap.get(WebConstants.ORDERTYPE));
		String currentPage=StringUtil.getStringFromObj(paramsMap.get(WebConstants.CURRENTPAGE));
		String changeType=StringUtil.getStringFromObj(paramsMap.get(WebConstants.CHANGETYPE));
		
		//2.获取组装的sql
		String queryString=QueryUtil.generateQuerySql(paramsMap);
		//查询记录总数
		String whereSql="";
		whereSql=getDialect().populatePageHQL(queryString,this.getBaseDao().getNameSpace());
		if(paramsMap.get("deptId")!=null&&!"1".equals(paramsMap.get("deptId"))){
			if(whereSql.indexOf("where",whereSql.lastIndexOf("SYS_USER"))>-1){
				whereSql+=" and idf in (select ud.useridf from SYS_USER_DEPT ud where ud.deptIdf='"+paramsMap.get("deptId")+"')";
			}else{
				whereSql+=" where idf in (select ud.useridf from SYS_USER_DEPT ud where ud.deptIdf='"+paramsMap.get("deptId")+"')";
			}
		}
		int totalCount=this.getBaseDao().getTotalPageCount("getTotalPageCount",whereSql);
		//3.创建分页对象 并对数据进行计算
		Pagination page=new Pagination(totalCount,getRowsPerPage());
		page.doPagination(changeType, currentPage);
		
		//4.查询数据
		if(paramsMap.get("deptId")!=null&&!"1".equals(paramsMap.get("deptId"))){
			if(queryString!=null&&queryString.length()>0){
				queryString+=" and idf in (select ud.useridf from SYS_USER_DEPT ud where ud.deptIdf='"+paramsMap.get("deptId")+"')";
			}else{
				queryString+=" idf in (select ud.useridf from SYS_USER_DEPT ud where ud.deptIdf='"+paramsMap.get("deptId")+"')";
			}
		}
		whereSql=getDialect().populatePageHQL2(queryString,orderByfields,orderType,page,this.getBaseDao().getNameSpace());
		List<BaseVo> list = (List<BaseVo>) this.getBaseDao().toList("toList",whereSql);
		page.setData(list);
		return new Result(ActionConstants.SUCCESS,page);
	}

	public Result toRoleList(String sql) throws Exception {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		List<BaseVo> list = (List<BaseVo>) this.getBaseDao().toList("toRoleList",sql);
		resultMap.put("roleList", list);
		return new Result(ActionConstants.SUCCESS,resultMap);
	}

	public String doInsertUsers(List<?> users,String deptId) throws Exception{
		this.getLogger().info("=========deptId===="+deptId);
		for(int i=0;i<users.size();i++){
			UserVo user=(UserVo)users.get(i);
			SysUserDeptVO udvo=new SysUserDeptVO();
			List result=toCheckData("WHERE userNamef='"+user.getUserNamef()+"'");
			boolean b=result.size()>0?false:true;
			if(b){
				if (StringUtil.isNullorEmpty(user.getIdf())||"null".equals(user.getIdf())) {
					user.setIdf(IDManager.generateID());
				}
				if (user.getDatasortNumf() == 0) {
					user.setDatasortNumf(System.currentTimeMillis());
				}
				user.setUserPwdf(MD5Util.getMD5(user.getUserPwdf()));// 对密码进行md5加密
				user.setCreatedate(DateUtil.getFullDate_());
				this.getBaseDao().doInsert("doInsert", user);
				udvo.setIdf(IDManager.generateID());
				udvo.setDeptIdf(deptId);
				udvo.setUseridf(user.getIdf());
				this.getBaseDao().doInsert("doInsertUD", udvo);
				//count++;
			}else{
				//this.getBaseService().doUpdate(user);
				//failList.add(user);
			}
		}
		
		return ActionConstants.RELOAD;
	}
	
	/**
	 * 重写用于处理密码加密并且分配角色
	 */
	@Override
	public String doInsertUsersb(List<?> users,String[] roles,String deptId) throws Exception {
		this.getLogger().info("=========deptId===="+deptId);
		for(int i=0;i<users.size();i++){
			UserVo user=(UserVo)users.get(i);
			SysUserDeptVO udvo=new SysUserDeptVO();
			SysUserRoleVO urvo=new SysUserRoleVO();
			List result=toCheckData("WHERE userNamef='"+user.getUserNamef()+"'");
			boolean b=result.size()>0?false:true;
			if(b){
				if (StringUtil.isNullorEmpty(user.getIdf())||"null".equals(user.getIdf())) {
					user.setIdf(IDManager.generateID());
				}
				if (user.getDatasortNumf() == 0) {
					user.setDatasortNumf(System.currentTimeMillis());
				}
				user.setUserPwdf(MD5Util.getMD5(user.getUserPwdf()));// 对密码进行md5加密
				user.setCreatedate(DateUtil.getFullDate_());
				this.getBaseDao().doInsert("doInsert", user);
				udvo.setIdf(IDManager.generateID());
				udvo.setDeptIdf(deptId);
				udvo.setUseridf(user.getIdf());
				this.getBaseDao().doInsert("doInsertUD", udvo);
				
				urvo.setIdf(IDManager.generateID());
				urvo.setUseridf(user.getIdf());
				if(roles!=null){
					for(int j=0;j<roles.length;j++){
						urvo.setRoleIdf(roles[j]);
						this.getBaseDao().doInsert("doInsertUserRole", urvo);
					}
				}
				//count++;
			}else{
				//this.getBaseService().doUpdate(user);
				//failList.add(user);
			}
		}
		
		return ActionConstants.RELOAD;
	}

}
